const { ipcRenderer, remote } = require("electron");
const fs = require('fs');

function $ (id) {
    return document.getElementById(id)
}

function getE (id) {
    return document.querySelector(id)
}

$('tooltip1').addEventListener('click', () => {
    ipcRenderer.send('open-files')
})

$('tooltip3').addEventListener('click', () => {
    var content = $('left-txt').value
    var filename = $('header-info').value
    ipcRenderer.send('save-file', content, filename)    
    remote.getGlobal('shareObject').update = true
})

ipcRenderer.on('save-success', (event, message) => {
    console.log(message)
    if (message) {
        $('tip-txt').innerHTML = '文件保存成功'
        
    } else {
        $('tip-txt').innerHTML = '文件保存失败，请重新保存'
    }
    $('tip').style.display = 'block'
    setTimeout(() => {
        $('tip').style.display = 'none'
    }, 1000)
})

function update () {
    console.log(remote.getGlobal('shareObject').calc)
    var name = remote.getGlobal('shareObject').calc;
    var fileName = './files/' + name + '.txt'; 
    if (name !== 'default') {
        fs.readFile(fileName, 'utf-8', (err, data) => {
            if (err) {
            } else {
                getE('textarea').value = data
                $('header-info').value = name
            }
        })
    }
}

update()